<?php
/**
 * Created by PhpStorm.
 * User: sunzexin
 * Date: 2018/1/8
 * Time: 16:36
 */

namespace App\Http\Logics\MiniProgramAdmin;

use App\Cafe;
use App\CafeMappingUser;
use App\City;
use App\Menu;
use App\Partner;
use App\Role;
use App\RoleMappingMenu;
use App\UserFollowCity;
use App\UserMappingCity;
use App\UserMappingRole;
use App\Users;
use Illuminate\Support\Facades\DB;
use App\Http\Logics\BaseLogic;
class RoleLogic extends BaseLogic
{
    public static function createRole($data)
    {
        try {
            $role = new Role();
            $role->name = $data['name'];
            $role->type = $data['type'];
            if (!$role->save()) {
                return self::response(self::OBJECT_DELETE_FAILD);
            }
            return self::response(self::SUCCESS);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    public static function createMiniProgram($data)
    {
        try {
            // 创建事务,创建一个小程序的同时往partner表中插入数据
            DB::transaction(function () use ($data) {
                $role = new Role();
                $role->name = $data['name'];
                $role->type = $data['type'];
                if (!$role->save()) {
                    return self::response(self::OBJECT_DELETE_FAILD);
                }
                $partner = new Partner();
                $partner->role_id = $role->id;
                $partner->app_key = $data['app_key'];
                $partner->appid = $data['appid'];
                $partner->secret = $data['secret'];
                // 为该小程序生成key，并且防止重复
                $flag = true;
                while ($flag){
                    $key = randomStr(10);
                    $partner_two = Partner::where('key', $key)->first();
                    if (empty($partner_two)){
                        $flag = false;
                    }
                }
                $partner->key = $key;
                $partner->name = $data['name'];
                if (!$partner->save()) {
                    return self::response(self::OBJECT_SAVE_FAIL);
                }
            });
            return self::response(self::SUCCESS);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    public static function getMiniProgramList($data)
    {
        try {
            $query = new Role();
            $query = $query->with(['partner'])->where(function ($query) use ($data){
                if (!empty($data['name'])){
                    $query->where('name', 'like', '%' . $data['name'] . '%');
                }
            })->where('type', $data['type'])->orderBy('id', 'desc');
            $role = $data['limit'] ? $query->paginate($data['limit']) : $query->get();
            if (empty($role)) {
                return self::response(self::CONTENT_IS_EMPTY);
            }
            return self::response(self::SUCCESS, $role);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    public static function deleteMiniProgram($data)
    {
        try {
            $partner = Partner::where('role_id', $data)->first();
            if (empty($partner)){
                return self::response(self::CONTENT_IS_EMPTY);
            }
            if (!$partner->delete()){
                return self::response(self::OBJECT_DELETE_FAILD);
            }

            $role = Role::find($data['id']);
            if (!$role->delete()) {
                return self::response(self::OBJECT_DELETE_FAILD);
            }
            return self::response(self::SUCCESS);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 删除角色
     * @param $data 筛选条件
     * @return mixed 返回结果
     * @throws \Exception
     */
    public static function deleteRole($data)
    {
        try {
            $role = Role::find($data['id']);
            if (!$role->delete()) {
                return self::response(self::OBJECT_DELETE_FAILD);
            }
            return self::response(self::SUCCESS);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    public static function getRoleList($data)
    {
        try {
            $role = Role::where('type', $data['type'])->orderBy('sort')->get()->groupBy('mark');
            if (empty($role)) {
                return self::response(self::CONTENT_IS_EMPTY);
            }
            return self::response(self::SUCCESS, $role);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    public static function setRoleMenu($data)
    {
        try {
            // 创建事务,给用户分配角色的一系列操作并且更新用户角色
            DB::transaction(function () use ($data) {

                RoleMappingMenu::where('role_id', $data['role_id'])->delete();

                $menu_list_arr = explode(',', $data['menu_list']);
                errorLog(is_nan($menu_list_arr[0]));
                if (!is_nan($menu_list_arr[0])) {
                    foreach ($menu_list_arr as $item) {
                        $role_mapping_menu = new RoleMappingMenu();
                        $role_mapping_menu->role_id = $data['role_id'];
                        $role_mapping_menu->menu_id = $item;
                        if (!$role_mapping_menu->save()) {
                            return self::response(self::OBJECT_SAVE_FAIL);
                        }
                    }
                }
            });
            return self::response(self::SUCCESS);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    public static function getRoleMenuList($data)
    {
        try {
            $role_mapping_menu = RoleMappingMenu::where('role_id', $data['role_id'])->get();
            if (!empty($role_mapping_menu)) {
                $role_menu_list_arr = [];
                foreach ($role_mapping_menu as $item) {
                    array_push($role_menu_list_arr, $item->menu_id);
                }
            }
            $role_menu_list_string = implode(',', $role_menu_list_arr);
            return self::response(self::SUCCESS, $role_menu_list_string);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    public static function getMiniProgramUserMenuList($data)
    {
        $role = Role::with(['menu' => function ($query){
            $query->where('type', Menu::COMMON_MENU);
        }])->find($data['role_id']);
        if (empty($role)) {
            return self::response(self::CONTENT_IS_EMPTY);
        }
        return self::response(self::SUCCESS, $role);
    }

    /**
     * 获取角色详情
     * @param $data
     * @return mixed
     */
    public static function getRoleDetail($data){
        $role = Role::find($data['role_id']);
        if (empty($role)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        return self::response(self::SUCCESS, $role);
    }
}